package com.qzdsoft.erpcloud.interceptor;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.qzdsoft.erpcloud.domain.sys.LoginUser;
import com.qzdsoft.erpcloud.service.sys.Permission;
import com.qzdsoft.erpcloud.service.sys.RedisService;
import com.qzdsoft.utils.JsonUtils;
import com.qzdsoft.utils.constant.RedisConstant;

/**
 *
 * 登录权限拦截器
 *
 * <p>detailed comment
 * @author pc-20170420 2017年9月12日
 * @see
 * @since 1.0
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor
{
    private static final Logger logger = LoggerFactory.getLogger(PermissionInterceptor.class);
    
    @Autowired
    private RedisService redisService;
    
    @Value("${permission.validate}")
    private Boolean permissionValidate;

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception
    {
        
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception
    {
        
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
         //如果配置文件配置不需要权限验证 直接返回true （开发时可以配置为false）
        if(!permissionValidate) {
            return true;
        }
        String pathURI = request.getRequestURI();
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            /*
            * 1、确认当前的controller是否需要进行权限判定，如果需要则进行验证。
            * 2、当controller不需要验证，则验证当前的方法是否需要权限验证，需要则进行验证，不需要则跳出
            * */
            //获取方法注解，方法检查是否需要验证权限控制
           Permission permission = handlerMethod.getMethod().getAnnotation(Permission.class);
           if (permission != null && !permission.validate()) //不需要验证权限
           {
               return true;
           }
            // 权限判断,没有权限则跳转至无权限页面，有权限则走正常流程
           else {
               LoginUser user = (LoginUser)request.getAttribute("user");
               Object menuObj = redisService.get(RedisConstant.reidsAuthorizedUrl+"_"+user.getId());
               if(menuObj!=null) {
                   logger.debug("======访问权限列表：{}",menuObj);
                   List<String> authorizedUrls  = JsonUtils.jsonToList(menuObj.toString(), String.class);
                   logger.debug("访问链接：{},是否含此链接访问权限：{}",pathURI,authorizedUrls.contains(pathURI));
                   if(!CollectionUtils.isEmpty(authorizedUrls)&&authorizedUrls.contains(pathURI)){
                       return true;
                   }else {
                       logger.debug("是否为ajax请求:{}",isAjaxRequest(request));
                       if(isAjaxRequest(request))// 如果是ajax请求响应头会有，x-requested-with；
                        {
                            response.setHeader("permission", "false");// 在响应头设置permission状态
                            return false;
                        }else {
                            response.sendRedirect("/401");
                            return false; 
                        }
                     
                   }
                   
               }
           }
       }
        return true;
    }
    private boolean isAjaxRequest(HttpServletRequest request) {
        return request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest");// 如果是ajax请求响应头会有，x-requested-with；
    }

}
